package com.lee.lease.web.admin.service.impl;

import com.lee.lease.common.minio.MinioProperties;
import com.lee.lease.web.admin.service.FileService;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String upload(MultipartFile file) {
        try {

            //判断bucket是否存在
            boolean found =
                    minioClient.bucketExists(
                            BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build()
                    );

            //如果不存在则创建bucket
            if (!found) {
                // 创建bucket
                minioClient.makeBucket(
                        MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build()
                );

                String policyJson = createBucketPolicyConfig(minioProperties.getBucketName());
                minioClient.setBucketPolicy(
                        SetBucketPolicyArgs.builder().bucket(minioProperties.getBucketName()).config(policyJson).build());
            }

            String currentDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String filename = currentDate + "/" + UUID.randomUUID() + "-" + file.getOriginalFilename();

            //parSize：分片参数
            // -1 ： 根据fileSize的大小自动进行分片上传
            // > 0：设置分片大小
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(minioProperties.getBucketName()).object(filename).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            //不设置contentType：下载文件
                            //设置contentType：预览文件
                            .contentType(file.getContentType())
                            .build());
            System.out.println("上传成功");
            String url = String.join(
                    "/",
                    minioProperties.getEndpoint(),
                    minioProperties.getBucketName(),
                    filename);

            return url;

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("失败 occurred: " + e);
            System.out.println("HTTP trace: " + e.getStackTrace());
        }

        return null;
    }

    private String createBucketPolicyConfig(String bucketName) {
        return """
                {
                  "Statement" : [ {
                    "Action" : "s3:GetObject",
                    "Effect" : "Allow",
                    "Principal" : "*",
                    "Resource" : "arn:aws:s3:::%s/*"
                  } ],
                  "Version" : "2012-10-17"
                }
                """.formatted(bucketName);
    }
}
